package cn.mugutu.finance.listener;

import cn.mugutu.finance.domain.system.User;
import cn.mugutu.finance.utils.ConstantConfig;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Map;

@WebListener
public class SessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        User user = (User) se.getSession().getAttribute(ConstantConfig.USER_IN_SESSION);
        if (user != null) {
            Map<String, HttpSession> onlineUsers = (Map<String, HttpSession>) se.getSession().getServletContext().getAttribute(
                    ConstantConfig.ONLINE_USER_LIST);
            if (onlineUsers != null) {
                onlineUsers.remove(user.getUsername());
                se.getSession().getServletContext().setAttribute(ConstantConfig.ONLINE_USER_LIST, onlineUsers);
            }
        }

    }

}
